<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item>
        <el-select size="small" v-model="type1" placeholder="请选择轮播图类型">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="chongzhi">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border
      element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="index" width="60" label="序号">
      </el-table-column>
      <el-table-column align="center" sortable prop="type" :formatter="Type" label="轮播图类型"
        width="120"></el-table-column>
      <el-table-column align="center" prop="url" label="主图" width="230">
        <template slot-scope="scope">
          <el-image style="width:180px;" :src="scope.row.url" :preview-src-list="[scope.row.url]"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="urls" label="跳转路径" width="220"></el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteCarouselData(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="50%" @click="closeDialog">
      <el-form label-width="120px" ref="editForm">
        <el-form-item label="轮播图类型">
          <el-select v-model="type" placeholder="请选择轮播图类型">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片">
          <div class="upload-demo">
            <el-upload action="" :http-request="mainImgUpload" :show-file-list="false" list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-image style="width:146px;height: 146px; margin-left: 24px;" :src="url" :preview-src-list="[url]"
              v-if="url"></el-image>
          </div>
        </el-form-item>
        <el-form-item label="跳转路径" v-if="type === 0">
          <el-input v-model="urls" auto-complete="off" placeholder="请输入跳转路径"></el-input>
        </el-form-item>
        <el-form-item label="跳转路径" v-if="type === 1">
          <span v-if="urls.constructor !== Number" style="font-size: 16px; color: black;">{{ urls }}</span>
          <span v-else style="font-size: 16px; color: black;">{{ "/pages/shopping_mall/goods_details?id=" + urls
            }}</span><br>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="Xuanze()">选择商品</el-button>
        </el-form-item>
        <el-dialog title="选择商品" :visible.sync="editFormVisibleXuanze" width="80%" @click="closeDialog"
          :modal-append-to-body="false" :append-to-body="true">
          <!-- 列表 -->
          <el-table size="small" ref="multipleTable" :data="GoodsData" highlight-current-row v-loading="loading" border
            element-loading-text="拼命加载中" style="width: 100%;" v-horizontal-scroll>
            <el-table-column align="center" sortable prop="sort" label="排序" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="name" label="商品名" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="categoryName" label="商品类别" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="buyPrice" label="会员优惠价" width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.buyPrice / 100 }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="buyPoint" label="所需积分" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="priceType" label="价格类型" :formatter="PriceType"
              width="120"></el-table-column>
            <el-table-column align="center" sortable prop="image" label="商品封面图" width="120">
              <template slot-scope="scope">
                <el-image v-if="scope.row.image != ''" :src="scope.row.image" :preview-src-list="[scope.row.image]"
                  style="width: 80px;"></el-image>
                <div v-if="scope.row.image == null">没有图片</div>
              </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="entity" :formatter="isShiti" label="是否实体"
              width="120"></el-table-column>
            <el-table-column align="center" sortable prop="totalCount" label="商品总数" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="saleCount" label="销量数量" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="inventoryCount" label="库存" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="isDisable" :formatter="isXiajia" label="是否下架"
              width="120"></el-table-column>
            <el-table-column align="center" sortable prop="postAddress" label="发货地址" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="virtualPrice" label="产品原价" width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.virtualPrice / 100 }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="addXuanze(scope.row)">确定选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="closeDialogXuanze">取消</el-button>
          </div>
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="addCarouselData()"
          v-if="title == '添加'">添加</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="upCarouselData()"
          v-if="title == '修改'">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCarouselList,
  addCarousel,
  deleteCarousel,
  upCarousel,
  getCommodityList
} from "../../api/userMG";
import Pagination from "../../components/Pagination";
import client from "@/utils/ossClient.js";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: "添加",
      listData: [], //
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 10,
      },
      options: [{
        value: 0,
        label: '首页轮播图'
      }, {
        value: 1,
        label: '商城轮播图'
      }],
      url: '',
      type: '',
      urls: '',
      type1: '',
      editFormVisibleXuanze: false,
      GoodsData: []
    };
  },
  // 注册组件
  components: {
    Pagination,
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getCarouselListData()
    this.getDataCom()
  },
  computed: {},
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 价格类型
    PriceType: function (row) {
      if (row.priceType == 0) {
        return "积分"
      } else if (row.priceType == 1) {
        return "微信支付"
      } else if (row.priceType == 2) {
        return "积分加微信支付"
      }
    },
    // 是否实体
    isShiti: function (row) {
      if (row.entity == 0) {
        return "虚体"
      } else if (row.entity == 1) {
        return "实体"
      }
    },
    // 是否下架
    isXiajia: function (row) {
      if (row.isDisable == 0) {
        return "未下架"
      } else if (row.isDisable == 1) {
        return "已下架"
      }
    },
    // 选择商品
    addXuanze(row) {
      this.urls = `${this.$carouselUrl}${row.id}`
      this.editFormVisibleXuanze = false
    },
    // 关闭选择页面
    closeDialogXuanze() {
      this.editFormVisibleXuanze = false
      this.$message({
        type: 'info',
        message: '已取消选择'
      })
    },
    // 打开选择页面
    Xuanze() {
      this.editFormVisibleXuanze = true
    },
    // 获取商品列表
    getDataCom() {
      this.loading = true;
      getCommodityList().then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.GoodsData = res.data.list;
          return;
        } else {
          this.$Message({
            type: "info",
            message: res.msg
          })
        }
      })
    },
    // 搜索数据
    search() {
      this.getCarouselListData()
    },
    // 重置数据
    chongzhi() {
      this.type1 = ''
      this.getCarouselListData()
    },
    // 轮播图类型
    Type: function (row) {
      if (row.type == 0) {
        return '首页轮播图'
      } else if (row.type == 1) {
        return '商城轮播图'
      }
    },
    // 删除
    deleteCarouselData(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"))
      this.$prompt('请输入密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: '不可以空数据提交!'
      }).then(({ value }) => {
        if (value === userdata.menuTwo) {
          this.$confirm("确定要删除吗?", "信息", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
          })
            .then(() => {
              deleteCarousel({ id: row.id })
                .then((res) => {
                  if (res.code == 200) {
                    this.$message({
                      type: "success",
                      message: "已删除！",
                    });
                    this.getCarouselListData();
                  } else {
                    this.$message({
                      type: "info",
                      message: res.msg,
                    });
                  }
                })
                .catch((err) => {
                  this.loading = false;
                  this.$message.error("删除失败，请稍后再试！");
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
          this.$message({
            type: 'error',
            message: '密码错误'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });

    },

    //修改轮播图
    upCarouselData() {
      this.loading = true;
      upCarousel({
        id: this.id,
        type: this.type,
        url: this.url,
        // '/pages/shopping_mall/goods_details?id=' + 
        urls: this.urls
      }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisible = false
          this.$message({
            type: "success",
            message: res.msg,
          });
          this.getCarouselListData();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    //添加轮播图
    addCarouselData() {
      this.loading = true;
      addCarousel({
        id: '',
        type: this.type,
        url: this.url,
        // '/pages/shopping_mall/goods_details?id=' + 
        urls: this.urls
      }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisible = false
          this.$message({
            type: "success",
            message: res.msg,
          });
          this.getCarouselListData();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    //自定义上传方法..
    mainImgUpload(file) {
      //判断扩展名
      const tmpcnt = file.file.name.lastIndexOf(".");
      const exname = file.file.name.substring(tmpcnt + 1);
      const names = ["jpg", "jpeg", "webp", "png", "bmp"];
      if (names.indexOf(exname) < 0) {
        this.$message.error("不支持的格式!");
        return;
      }
      const fileName = file.file.uid + "." + exname;
      client
        .put(fileName, file.file)
        .then((res) => {
          if (res.url) {
            this.url = res.url;
          } else {
            this.$message.error("文件上传失败");
          }
        })
        .catch((err) => { });
    },


    // 获取轮播图
    getCarouselListData() {
      this.loading = true;
      getCarouselList({
        type: this.type1
      }).then((res) => {
        // return console.log(res.data.data);
        this.loading = false;
        if (res.code == 200) {
          this.listData = res.data.data;
          return;
        }
        this.$message({
          type: "info",
          message: res.msg,
        });
      });
    },

    // 分页插件事件
    callFather(parm) {
      this.getDishesList(parm.currentPage);
    },

    //显示编辑界面
    handleEdit: function (row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"))
      this.$prompt('请输入密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: '不可以空数据提交!'
      }).then(({ value }) => {
        if (value === userdata.menuTwo) {
          this.editFormVisible = true;
          if (row != undefined && row != "undefined") {
            this.title = "修改";
            this.id = row.id;
            this.type = row.type;
            this.url = row.url;
            this.urls = row.urls;
          } else {
            this.title = "添加";
            this.id = "";
            this.type = "";
            this.urls = "";
          }
        } else {
          this.$message({
            type: 'error',
            message: '密码错误'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
      this.$message({
        type: 'info',
        message: '已取消编辑'
      })
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}

.upload-demo {
  display: flex;
  flex-direction: row;
}

.upload-demo img {
  width: 140px;
  height: 140px;
}
</style>